<template>
  <div class="teacher-page">
    <div class="container">
      <h1 class="page-title">讲师团队</h1>
      
      <!-- 搜索和筛选 -->
      <div class="filter-bar card">
        <div class="filter-content">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索讲师姓名、专业领域"
            class="search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
          <el-select v-model="filterField" placeholder="专业领域" clearable @change="handleSearch">
            <el-option
              v-for="field in fields"
              :key="field.value"
              :label="field.label"
              :value="field.value"
            />
          </el-select>
          <el-select v-model="filterLevel" placeholder="讲师级别" clearable @change="handleSearch">
            <el-option
              v-for="level in levels"
              :key="level.value"
              :label="level.label"
              :value="level.value"
            />
          </el-select>
          <el-button type="primary" @click="resetFilters">重置筛选</el-button>
        </div>
      </div>

      <!-- 讲师列表 -->
      <div class="teacher-list">
        <div class="page-header card">
          <h2>讲师团队</h2>
          <el-button v-if="isAdmin" type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>添加讲师
          </el-button>
        </div>

        <div class="teacher-grid">
          <el-row :gutter="20">
            <el-col :span="6" v-for="teacher in paginatedTeachers" :key="teacher.id">
              <div class="teacher-card card">
                <div class="teacher-image" @click="viewTeacherDetail(teacher)">
                  <img :src="teacher.avatar" :alt="teacher.name">
                  <div class="teacher-level" :class="teacher.level">{{ teacher.levelText }}</div>
                </div>
                <div class="teacher-content">
                  <h3 @click="viewTeacherDetail(teacher)">{{ teacher.name }}</h3>
                  <p class="teacher-title">{{ teacher.title }}</p>
                  <p class="teacher-desc">{{ teacher.description }}</p>
                  <div class="teacher-info">
                    <div class="teacher-meta">
                      <span class="courses">
                        <el-icon><Collection /></el-icon>
                        {{ teacher.courseCount }}门课程
                      </span>
                      <span class="students">
                        <el-icon><UserFilled /></el-icon>
                        {{ teacher.studentCount }}名学生
                      </span>
                    </div>
                    <div class="teacher-rating">
                      <el-rate
                        v-model="teacher.rating"
                        disabled
                        show-score
                        text-color="#ff9900"
                      />
                    </div>
                  </div>
                  <div class="teacher-footer">
                    <div class="tags">
                      <el-tag
                        v-for="tag in teacher.tags"
                        :key="tag"
                        size="small"
                        class="tag"
                      >
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>
                  <div class="teacher-actions">
                    <el-button type="primary" @click="viewTeacherDetail(teacher)">查看详情</el-button>
                    <template v-if="isAdmin">
                      <el-button type="warning" @click.stop="handleEdit(teacher)">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                      <el-button type="danger" @click.stop="handleDelete(teacher)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </template>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 添加/编辑讲师对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑讲师' : '添加讲师'"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入讲师姓名" />
          </el-form-item>
          <el-form-item label="职称" prop="title">
            <el-input v-model="form.title" placeholder="请输入讲师职称" />
          </el-form-item>
          <el-form-item label="专业领域" prop="field">
            <el-input v-model="form.field" placeholder="请输入专业领域" />
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <el-input v-model="form.avatar" placeholder="请输入头像URL" />
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入讲师简介"
            />
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              placeholder="请选择或输入标签"
            >
              <el-option
                v-for="tag in tagOptions"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Collection, User, Star, Plus, Edit, Delete, UserFilled } from '@element-plus/icons-vue'
import { useTeacherStore } from '@/stores/teacher'

const router = useRouter()
const teacherStore = useTeacherStore()
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

// 搜索和筛选
const searchKeyword = ref('')
const filterField = ref('')
const filterLevel = ref('')

// 专业领域选项
const fields = [
  { label: '前端开发', value: 'frontend' },
  { label: '后端开发', value: 'backend' },
  { label: '移动开发', value: 'mobile' },
  { label: '人工智能', value: 'ai' },
  { label: '数据科学', value: 'data' },
  { label: '云计算', value: 'cloud' }
]

// 讲师级别选项
const levels = [
  { label: '高级讲师', value: 'senior' },
  { label: '资深讲师', value: 'expert' },
  { label: '特级讲师', value: 'master' }
]

// 获取讲师列表
const teacherList = ref([])

// 管理员状态
const isAdmin = computed(() => localStorage.getItem('role') === 'admin')

// 表单数据
const form = ref({
  name: '',
  title: '',
  field: '',
  avatar: '',
  description: '',
  tags: [],
  courseCount: 0,
  studentCount: 0,
  rating: 5
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入讲师姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入讲师职称', trigger: 'blur' }
  ],
  field: [
    { required: true, message: '请输入专业领域', trigger: 'blur' }
  ],
  avatar: [
    { required: true, message: '请输入头像URL', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入讲师简介', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请选择标签', trigger: 'change' }
  ]
}

// 标签选项
const tagOptions = [
  '前端开发',
  '后端开发',
  '移动开发',
  '数据库',
  '人工智能',
  '云计算',
  '运维',
  '测试',
  'UI设计',
  '产品经理'
]

// 过滤后的讲师列表
const filteredTeachers = computed(() => {
  if (!Array.isArray(teacherList.value)) return []
  
  return teacherList.value.filter(teacher => {
    const matchKeyword = !searchKeyword.value || 
      teacher.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      teacher.description.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (teacher.tags && teacher.tags.some(tag => tag.toLowerCase().includes(searchKeyword.value.toLowerCase())))
    
    const matchField = !filterField.value || teacher.field === filterField.value
    const matchLevel = !filterLevel.value || teacher.level === filterLevel.value
    
    return matchKeyword && matchField && matchLevel
  })
})

// 分页后的讲师列表
const paginatedTeachers = computed(() => {
  return filteredTeachers.value
})

// 搜索处理
const handleSearch = () => {
  // 可以在这里添加额外的搜索逻辑
}

// 查看讲师详情
const viewTeacherDetail = (teacher) => {
  router.push({
    path: `/teacher/${teacher.id}`,
    query: {
      name: teacher.name,
      title: teacher.title,
      avatar: teacher.avatar,
      description: teacher.description,
      level: teacher.level,
      levelText: teacher.levelText,
      courseCount: teacher.courseCount,
      studentCount: teacher.studentCount,
      rating: teacher.rating,
      tags: JSON.stringify(teacher.tags),
      field: teacher.field
    }
  })
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  form.value = {
    name: '',
    title: '',
    field: '',
    avatar: '',
    description: '',
    tags: [],
    courseCount: 0,
    studentCount: 0,
    rating: 5
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (teacher) => {
  isEdit.value = true
  form.value = {
    id: teacher.id,
    name: teacher.name,
    title: teacher.title,
    field: teacher.field,
    avatar: teacher.avatar,
    description: teacher.description,
    tags: teacher.tags,
    level: teacher.level,
    courseCount: teacher.courseCount,
    studentCount: teacher.studentCount,
    rating: teacher.rating
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (teacher) => {
  ElMessageBox.confirm(
    '确定要删除该讲师吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = teacherList.value.findIndex(t => t.id === teacher.id)
    if (index !== -1) {
      teacherList.value.splice(index, 1)
      // 保存到 localStorage
      localStorage.setItem('teachers', JSON.stringify(teacherList.value))
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const teacherData = {
      id: isEdit.value ? form.value.id : Date.now(),
      name: form.value.name,
      title: form.value.title,
      field: form.value.field,
      avatar: form.value.avatar,
      description: form.value.description,
      tags: form.value.tags,
      level: isEdit.value ? form.value.level : 'senior',
      levelText: getLevelText(isEdit.value ? form.value.level : 'senior'),
      courseCount: isEdit.value ? form.value.courseCount : 0,
      studentCount: isEdit.value ? form.value.studentCount : 0,
      rating: isEdit.value ? form.value.rating : 5
    }
    
    if (isEdit.value) {
      const index = teacherList.value.findIndex(t => t.id === teacherData.id)
      if (index !== -1) {
        teacherList.value[index] = teacherData
      }
    } else {
      teacherList.value.unshift(teacherData)
    }
    
    // 保存到 localStorage
    localStorage.setItem('teachers', JSON.stringify(teacherList.value))
    
    ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 获取等级文本
const getLevelText = (level) => {
  const levelMap = {
    'junior': '初级讲师',
    'intermediate': '中级讲师',
    'senior': '高级讲师',
    'expert': '专家讲师'
  }
  return levelMap[level] || '高级讲师'
}

// 初始化时从 localStorage 加载数据
const loadTeachersFromStorage = () => {
  const storedTeachers = localStorage.getItem('teachers')
  if (storedTeachers) {
    teacherList.value = JSON.parse(storedTeachers)
  } else {
    // 如果没有存储的数据，使用默认数据
    teacherList.value = [
      {
        id: 1,
        name: '张教授',
        title: '前端技术专家',
        field: 'frontend',
        avatar: 'https://picsum.photos/200/200?random=1',
        description: '10年前端开发经验，精通Vue、React等主流框架，曾就职于多家知名互联网公司。',
        tags: ['Vue.js', 'React', 'TypeScript', '前端工程化'],
        level: 'senior',
        levelText: '高级讲师',
        courseCount: 15,
        studentCount: 5000,
        rating: 4.9
      },
      {
        id: 2,
        name: '李博士',
        title: '人工智能专家',
        field: 'ai',
        avatar: 'https://picsum.photos/200/200?random=2',
        description: '人工智能领域专家，专注于机器学习、深度学习研究，发表多篇SCI论文。',
        tags: ['机器学习', '深度学习', 'Python', 'TensorFlow'],
        level: 'expert',
        levelText: '资深讲师',
        courseCount: 12,
        studentCount: 3000,
        rating: 4.8
      },
      {
        id: 3,
        name: '王老师',
        title: '后端架构师',
        field: 'backend',
        avatar: 'https://picsum.photos/200/200?random=3',
        description: '8年Java开发经验，精通微服务架构，对高并发、分布式系统有深入研究。',
        tags: ['Java', 'Spring Cloud', '微服务', '分布式系统'],
        level: 'master',
        levelText: '特级讲师',
        courseCount: 20,
        studentCount: 8000,
        rating: 4.95
      },
      {
        id: 4,
        name: '陈老师',
        title: '移动开发专家',
        field: 'mobile',
        avatar: 'https://picsum.photos/200/200?random=4',
        description: '专注于iOS和Android开发，对移动端性能优化和架构设计有丰富经验。',
        tags: ['iOS', 'Android', 'Flutter', '移动开发'],
        level: 'senior',
        levelText: '高级讲师',
        courseCount: 10,
        studentCount: 2500,
        rating: 4.7
      },
      {
        id: 5,
        name: '刘博士',
        title: '数据科学专家',
        field: 'data',
        avatar: 'https://picsum.photos/200/200?random=5',
        description: '数据分析和挖掘专家，擅长大数据处理、数据可视化，有丰富的项目经验。',
        tags: ['数据分析', '数据挖掘', 'Python', '大数据'],
        level: 'expert',
        levelText: '资深讲师',
        courseCount: 8,
        studentCount: 2000,
        rating: 4.85
      }
    ]
    // 保存默认数据到 localStorage
    localStorage.setItem('teachers', JSON.stringify(teacherList.value))
  }
}

// 在组件挂载时加载数据
onMounted(() => {
  loadTeachersFromStorage()
})

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = ''
  filterField.value = ''
  filterLevel.value = ''
  handleSearch()
}
</script>

<style scoped>
.teacher-page {
  padding: 20px;
  background-color: var(--bg-color);
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  margin-bottom: 30px;
  font-size: 28px;
  color: var(--text-primary);
  text-align: center;
  font-weight: bold;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.filter-bar {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 300px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--text-primary);
}

.teacher-grid {
  margin-bottom: 20px;
}

.teacher-card {
  height: 100%;
  transition: transform 0.3s ease;
  margin-bottom: 20px;
}

.teacher-card:hover {
  transform: translateY(-5px);
}

.teacher-image {
  position: relative;
  height: 200px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 8px 8px 0 0;
}

.teacher-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.teacher-card:hover .teacher-image img {
  transform: scale(1.05);
}

.teacher-level {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
  background: rgba(0, 0, 0, 0.6);
}

.teacher-level.senior {
  background: #67c23a;
}

.teacher-level.expert {
  background: #e6a23c;
}

.teacher-level.master {
  background: #f56c6c;
}

.teacher-content {
  padding: 20px;
}

.teacher-content h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: var(--text-primary);
  cursor: pointer;
  transition: color 0.3s ease;
}

.teacher-content h3:hover {
  color: var(--primary-color);
}

.teacher-title {
  margin: 0 0 10px;
  font-size: 14px;
  color: var(--text-secondary);
}

.teacher-desc {
  margin: 0 0 15px;
  font-size: 14px;
  color: var(--text-secondary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
  height: 42px;
}

.teacher-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.teacher-meta {
  display: flex;
  gap: 12px;
  color: var(--text-light);
  font-size: 14px;
}

.teacher-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.teacher-rating {
  margin-bottom: 15px;
}

.teacher-footer {
  margin-bottom: 15px;
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  margin-right: 4px;
}

.teacher-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.teacher-actions .el-button {
  flex: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
  }
  
  .search-input {
    width: 100%;
  }
  
  .el-col {
    width: 100%;
  }
  
  .teacher-card {
    margin-bottom: 20px;
  }
}
</style> 